package cc.vv.baselibrary.view.banner;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Scroller;

import java.lang.reflect.Field;
import java.util.ArrayList;

import cc.vv.baselibrary.R;
import cc.vv.lkbasecomponent.util.LKScreenUtil;
import cc.vv.lkimagecomponent2.LKImage;
import cc.vv.lkimagecomponent2.lib.mode.ScaleMode;
import cc.vv.lklibrary.log.LogOperate;


/**
 * 图片类型 Banner VIEW
 *
 * @author: NPF
 * @date: 2018/1/27.
 */
public class ImgBannerView extends RelativeLayout {
    private ViewPager vp_imgBanner;
    private LinearLayout ll_imgBanner;
    private Context mContext;
    /**
     * Banner点击事件回调
     */
    private ImgBannerClickInter mInter;
    /**
     * 自动滑动用
     */
    private Handler mHandler;
    /**
     * VP默认高度
     */
    private int mVpHeight = 0;
    /**
     * 指示器默认宽高
     */
    private int mImgIndicatorWH = 10;
    /**
     * 指示器默认间距
     */
    private int mImgIndicatorSpace = 10;

    /**
     * 图片集合
     */
    private ArrayList<String> mImgPaths;
    /**
     * 默认图片ID
     */
    private int mDefImgID = -1;

    /**
     * 指示器默认图片ID
     */
    private int mDefIndicatorImgID = -1;
    /**
     * 指示器选中图片ID
     */
    private int mSelectedIndicatorImgID = -1;
    /**
     * 消息what
     */
    private final int HANDLER_WHAT = 101;
    /**
     * 自动轮播间隔时间
     */
    private final long TIME_SPACE = 10000;


    public ImgBannerView(Context context) {
        this(context, null);
    }

    public ImgBannerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ImgBannerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        initView();
    }

    /**
     * 初始化布局
     */
    private void initView() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.view_banner_img, null);
        this.addView(view);
        vp_imgBanner = view.findViewById(R.id.vp_imgBanner);
        ll_imgBanner = view.findViewById(R.id.ll_imgBanner);
    }


    /**
     * 设置宽高比例,在调用initImgData之前调用
     *
     * @param wPercentage 比例：宽
     * @param hPercentage 比例：高
     * @param defImgID    与宽高比例相符合的默认图片id
     * @return
     */
    public ImgBannerView initWHPercentage(int wPercentage, int hPercentage, int defImgID) {
        if (defImgID > 0) mDefImgID = defImgID;
        if (wPercentage < 1) wPercentage = 1;
        if (hPercentage < 1) hPercentage = 1;
        int screenWidth = LKScreenUtil.getScreenWidth();
        mVpHeight = screenWidth * hPercentage / wPercentage;
        ViewGroup.LayoutParams layoutParams = vp_imgBanner.getLayoutParams();
        layoutParams.width = screenWidth;
        layoutParams.height = mVpHeight;
        vp_imgBanner.setLayoutParams(layoutParams);
        return this;
    }


    /**
     * 初始化数据源、事件回调
     *
     * @param imgPaths 图片路径集合
     * @param inter    点击事件回调
     */
    public ImgBannerView initImgData(ArrayList<String> imgPaths, ImgBannerClickInter inter) {
        if (0 == mVpHeight) {
            throw new IllegalStateException("initImgData()必须再函数initWHPercentage()之后调用");
        }
        if (null == imgPaths) {
            throw new IllegalStateException("Banner数据源为null");
        }
        if (0 == imgPaths.size()) {
            this.setVisibility(GONE);
            LogOperate.e("Banner数据源大小为0");
            return this;
        }
        mImgPaths = imgPaths;
        mInter = inter;
        vp_imgBanner.setAdapter(null);
        ImgPagerAdapter adapter = new ImgPagerAdapter();
        vp_imgBanner.setAdapter(adapter);
        return this;
    }


    /**
     * 初始化并显示指示器控件
     *
     * @param defIndicatorImgID      默认图片
     * @param selectedIndicatorImgID 选中图片
     * @param imgIndicatorWH         图片指示器宽高
     * @param imgIndicatorSpace      图片指示器间距
     * @return
     */
    @SuppressLint("NewApi")
    public ImgBannerView initIndicatorView(int defIndicatorImgID, int selectedIndicatorImgID, int imgIndicatorWH, int imgIndicatorSpace) {
        if (null == vp_imgBanner.getAdapter()) {
            throw new IllegalStateException("initPostionView()必须再函数initImgData()之后调用");
        }
        if (defIndicatorImgID < 1 || selectedIndicatorImgID < 1) {
            throw new IllegalStateException("无效的指示器状态图片");
        }
        mDefIndicatorImgID = defIndicatorImgID;
        mSelectedIndicatorImgID = selectedIndicatorImgID;
        if (imgIndicatorWH > 0) mImgIndicatorWH = imgIndicatorWH;
        if (imgIndicatorSpace > 0) mImgIndicatorSpace = imgIndicatorSpace;
        ll_imgBanner.removeAllViews();
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LKScreenUtil.dp2px(mImgIndicatorWH)
                , LKScreenUtil.dp2px(mImgIndicatorWH));
        layoutParams.setMarginStart(LKScreenUtil.dp2px(mImgIndicatorSpace));
        /**
         * 设置当前显示位置,主要是为了刚开始就可以左右都能滑动
         */
        vp_imgBanner.setCurrentItem(mImgPaths.size() * 100);
        /**
         * 对当前位置进行计算
         */
        int position = calculatePosition(vp_imgBanner.getCurrentItem());
        for (int i = 0; i < mImgPaths.size(); i++) {
            ImageView imageView = new ImageView(mContext);
            imageView.setLayoutParams(layoutParams);
            if (i == position) {
                imageView.setImageResource(selectedIndicatorImgID);
            } else {
                imageView.setImageResource(defIndicatorImgID);
            }
            ll_imgBanner.addView(imageView);
        }
        initPageChangeListener();
        initAutoPageChangeOperate();
        return this;
    }

    /**
     * 移出消息
     */
    public void clearMsg() {
        if (null != mHandler) {
            mHandler.removeMessages(HANDLER_WHAT);
        }
    }

    /**
     * 初始化页面滑动监听
     */
    private void initPageChangeListener() {
        setAutoScrollDurationTime(800);
        vp_imgBanner.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                initIndicatorViewState(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (0 == state) {
                    mHandler.sendEmptyMessageDelayed(HANDLER_WHAT, TIME_SPACE);
                } else {
                    mHandler.removeMessages(HANDLER_WHAT);
                }
            }
        });
    }


    /**
     * 初始化自动滑动操作
     */
    @SuppressLint("HandlerLeak")
    private void initAutoPageChangeOperate() {
        if (null == mHandler) {
            mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    vp_imgBanner.setCurrentItem(vp_imgBanner.getCurrentItem() + 1);
                }
            };
        }
        mHandler.sendEmptyMessageDelayed(HANDLER_WHAT, TIME_SPACE);
    }

    /**
     * 初始化图片状态
     *
     * @param position
     */
    private void initIndicatorViewState(int position) {
        position = calculatePosition(position);
        for (int i = 0; i < mImgPaths.size(); i++) {
            ImageView childAt = (ImageView) ll_imgBanner.getChildAt(i);
            if (position == i) {
                childAt.setImageResource(mSelectedIndicatorImgID);
            } else {
                childAt.setImageResource(mDefIndicatorImgID);
            }
        }
    }

    /**
     * 计算索引
     *
     * @param position
     * @return
     */
    private int calculatePosition(int position) {
        position %= mImgPaths.size();
        if (position < 0) {
            position = mImgPaths.size() + position;
        }
        return position;
    }

    /**
     * 设置自动滑动时间隔时间
     */
    public void setAutoScrollDurationTime(final int durationTime) {
        try {
            Field scrollerField = ViewPager.class.getDeclaredField("mScroller");
            scrollerField.setAccessible(true);
            Field interpolator = ViewPager.class.getDeclaredField("sInterpolator");
            interpolator.setAccessible(true);

            Scroller scroller = new Scroller(vp_imgBanner.getContext(), (Interpolator) interpolator.get(null)) {
                @Override
                public void startScroll(int startX, int startY, int dx, int dy, int duration) {
                    super.startScroll(startX, startY, dx, dy, durationTime);    // 这里是关键，将duration变长或变短
                }
            };
            scrollerField.set(vp_imgBanner, scroller);
        } catch (Exception e) {
            LogOperate.e(e.getMessage(), e);
        }

    }

    /**
     * Banner   适配器
     */
    private class ImgPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public ImageView instantiateItem(ViewGroup container, int position) {
            position = calculatePosition(position);
            String imgPath = mImgPaths.get(position);
            ImageView imageView = new ImageView(mContext);
            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setLayoutParams(layoutParams);
            if (mDefImgID > 0) {
                LKImage.load().load(imgPath).placeHolder(mDefImgID).error(mDefImgID)
                        .scale(ScaleMode.FIT_CENTER).into(imageView);

            } else {
                LKImage.load().load(imgPath).scale(ScaleMode.CENTER_CROP).into(imageView);
            }
            container.addView(imageView);
            initClickListener(imageView, position);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
        }

        /**
         * 初始化点击事件
         *
         * @param imageView
         * @param position
         */
        private void initClickListener(ImageView imageView, final int position) {
            imageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != mInter) {
                        mInter.bannerClickListener(mImgPaths.get(position), position);
                    }
                }
            });
        }
    }


    /**
     * Banner事件回调
     */
    public interface ImgBannerClickInter {
        void bannerClickListener(String imgPath, int position);
    }


}